<?php

/**
 * cpanel link management menu callback
 */
function cpanel_link_management($op = NULL) {
  global $user;
  $nips_per_page = 10;

  switch($op) {
    case 'get':
      CommonHelper::check_token('link_management');

      $query = db_select('node', 'n')->extend('PagerDefault');
      $query->fields('n', array('nid'));
      $query->condition('n.type', NIP_TYPE)
        ->condition('n.uid', $user->uid)
        ->orderBy('n.nid', 'DESC');

      $data = array(
        'count' => $query->countQuery()->execute()->fetchField(),
        'nips' => array(),
      );

      $query->limit($nips_per_page);
      $nids = $query->execute()->fetchCol();
      $nodes = node_load_multiple($nids);

      foreach($nodes as $node) {
        $field_board = field_get_items('node', $node, 'field_board');
        $tid = $field_board[0]['tid'];
        $data['nips'][] = array(
          'nid' => $node->nid,
          'board' => array(
            'tid' => $tid,
            'name' => TaxonomyHelper::taxonomy_get_term_name($tid),
            'url' => url("taxonomy/term/$tid"),
          ),
          'og_data' => $node->link_crabber->og_data,
          'url' => url("node/$node->nid"),
        );
      }

      drupal_json_output($data);
      break;

    case 'delete':
      CommonHelper::check_token('link_management');

      $data = $_POST;

      if(empty($data)) {
        drupal_access_denied();
        drupal_exit();
      }

      $nids = array();
      foreach($data['nips_selected'] as $nip) {
        $nids[] = $nip['nid'];
      }
      node_delete_multiple($nids);
      drupal_json_output(NULL);
      break;

    default:
      LibraryHelper::load(array(
        array('name' => 'angular'),
        array('name' => 'angular-utils-pagination'),
      ));

      drupal_add_js(array(
        'link_management' => array(
          'uid' => $user->uid,
          'nips_per_page' => $nips_per_page,
          'token' => drupal_get_token('link_management'),
        )
      ), 'setting');

      $cpanel = drupal_get_path('module', 'cpanel');
      drupal_add_css($cpanel . '/css/link_management.css');
      drupal_add_js($cpanel . '/js/link_management.js');

      return array('#theme' => 'cpanel_link_management');
      break;
  }
}
